/*
 ============================================================================
 Name        : searchExactPattern.c
 Author      : M.Barsky
 Version     :
 Copyright   : Your copyright notice
 Description : Blind Search for exact pattern in suffix tree
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include "SuffixTree.h"
#include "ExactSearch.h"


extern int maxOccurences;
extern DividerElement* dividers;
extern unsigned int totalDividers;

int main(int argc, char *argv[]) 
{

	int i;
	char inputfilenameprefix [MAX_PATH_LENGTH];
	char dividersFileName[MAX_PATH_LENGTH];
	char treeprefix [MAX_PATH_LENGTH];
	char *pattern;
	int patternLength;
	ResultRecord *occurences;
	int count;
	char *encodedDNA;
	char *buffer;
	FILE *dividersFile;
	
	if(argc<6)
	{
		printf("To run: ./search <treefolder> <treefileprefix> <dnapatterntosearch(lower case)> "
				"<patternlength> <maxNumberOfOccurencesToDisplay>\n");
		return 1;
	}

		

	pattern=argv[3];
	sprintf(inputfilenameprefix,"%s%s", argv[1], argv[2]);
	sprintf(treeprefix,"%s%s_tree", argv[1], argv[2]);
	patternLength =atoi(argv[4]);		
	maxOccurences=atoi(argv[5]);	
	
	occurences=(ResultRecord*) calloc (maxOccurences, sizeof(ResultRecord));
	encodedDNA=(char*) calloc (2*patternLength, sizeof(char));
	buffer=(char*) calloc (patternLength, sizeof(char));
	count=0;

  //2. Load dividers
	
	sprintf(dividersFileName,"%s_dividers",inputfilenameprefix);
	
	if(!(dividersFile= fopen ( dividersFileName , "rb" )))
	{
		printf("Could not open dividers DNA file \"%s\" \n", dividersFileName);
		return 1;
	}
	
	//determine number of dividers
	fseek (dividersFile, 0, SEEK_END);
	totalDividers=ftell (dividersFile)/sizeof(DividerElement);
	rewind(dividersFile);
	
	dividers=(DividerElement*) calloc (totalDividers, sizeof(DividerElement));
	
	if(fread (dividers,sizeof(DividerElement),totalDividers,dividersFile)!=totalDividers)
	{
		printf("Error reading tree dividers file \"%s\" \n", dividersFileName);
		return 1;
	}

	fclose(dividersFile);

	if(findAllOccurences(treeprefix,inputfilenameprefix,pattern,
			patternLength,occurences,&count,encodedDNA,buffer))
			return 1;	
	
	printf("Pattern %s occurs %d times, for example:\n",pattern,count);
	for(i=0;i<maxOccurences;i++)
	{
		printf("In file %i at position %d\n",occurences[i].fileNumber,occurences[i].startPos);
	}
	return 0;
}
